package com.example.gobang_system.common.util;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.json.JsonParseException;

import java.util.List;
import java.util.concurrent.Callable;

/**
 * 进行 序列化 和 反序列化
 */
public class JacksonUtil {
    private JacksonUtil() {}

    private final static ObjectMapper OBJECT_MAPPER;

    static {
        OBJECT_MAPPER = new ObjectMapper();
    }

    private static ObjectMapper getObjectMapper() {
        return OBJECT_MAPPER;
    }

    /**
     * 序列化
     * @param value
     * @return
     */
    public static String writeValueAsString(Object value) {
        return tryParse(() ->
                getObjectMapper().writeValueAsString(value));
    }


    /**
     * 反序列化
     * @param content
     * @param valueType
     * @return
     * @param <T>
     */
    public static <T> T readValue(String content, Class<T> valueType) {
        return tryParse(() -> {
            return getObjectMapper().readValue(content, valueType);
        });
    }

    /**
     * 反序列化 List
     * @param content
     * @param param List 中元素类型
     * @return
     */
    public static <T> T readListValue(String content, Class<?> param) {
        JavaType javaType = getObjectMapper().getTypeFactory()
                .constructParametricType(List.class, param);
        return tryParse(() -> {
            return getObjectMapper().readValue(content, javaType);
        });
    }

    private static <T> T tryParse(Callable<T> parser, Class<? extends Exception> check) {
        try {
            return parser.call();
        } catch (Exception e) {
            if (check.isAssignableFrom(e.getClass())) {
                throw new JsonParseException(e);
            }
            throw new IllegalStateException(e);
        }
    }

    private static <T> T tryParse(Callable<T> parser) {
        return tryParse(parser, JsonParseException.class);
    }
}